<template>
	<view class="cu-modal bottom-modal" :class="isShow == true?'show':''">
		<view class="cu-dialog">
			<view class="cu-bar bg-white" :style="{marginTop:CustomBar + 'px'}">
				<view class="action text-blue" @tap.stop="__cancel">取消</view>
				<view @tap.stop="clearAll" class="action text-blue">{{title}} ({{checkedNum}})</view>
				<view class="action text-green" @tap.stop="__confirm">确定</view>
			</view>
			<view class="cu-bar search bg-white border-bottom">
				<view class="search-form round">
					<text class="cuIcon-search"></text>
					<input v-model="searchText" :adjust-position="false" type="text" placeholder="关键字" confirm-type="search"></input>
				</view>
				
				<view class="action">
					<button class="cu-btn bg-green shadow-blur round" @tap.stop="search">搜索</button>
				</view>
			</view>
			<view class="bg-white">
				<scroll-view scroll-y="true" style="height: 75vh;text-align:left;">
					<view class="cu-list menu" v-if="checkbox">
						<view class="cu-item" v-if="val.show" v-for="(val,ind) in list" @tap.stop="getSubList(val.id, val.deep, ind)" :style="{marginLeft:val.deep*20+'px'}">
							<view class="content">
								<text class="text-green" v-if="val.isParent" :class="val.icon == 'down'?'cuIcon-unfold':'cuIcon-right'"></text>
								<text class="text-green" :class="icon"  v-if="val.isParent == false"></text>
								<text class="text-grey">{{val.name}}</text>
							</view>
							<checkbox v-if="val.isParent == false && checkbox == true" :value="val.id" :checked="val.checked" @tap.stop="checkboxChange(ind)"/>
							<radio v-if="val.isParent == false && checkbox == false" :class="val.checked?'checked':''" :checked="val.checked" :value="val.id" @tap.stop="radioChange(ind)"></radio>
						</view>
					</view>
					<radio-group style="display: block;">
					<view class="cu-list menu" v-if="!checkbox">
						
							<view class="cu-item" v-if="val.show" v-for="(val,ind) in list" @tap.stop="getSubList(val.id, val.deep, ind)" :style="{marginLeft:val.deep*20+'px'}">
								<view class="content">
									<text class="text-green" v-if="val.isParent" :class="val.icon == 'down'?'cuIcon-unfold':'cuIcon-right'"></text>
									<text class="text-green" :class="icon"  v-if="val.isParent == false"></text>
									<text class="text-grey">{{val.name}}</text>
								</view>
								<checkbox v-if="val.isParent == false && checkbox == true" :value="val.id" :checked="val.checked" @tap.stop="checkboxChange(ind)"/>
								<radio v-if="val.isParent == false && checkbox == false" :class="val.checked?'checked':''" :checked="val.checked" :value="val.id" @tap.stop="radioChange(ind)"></radio>
							</view>
						
					</view>
					</radio-group>
				</scroll-view>
			</view>
		</view>
	</view>
</template>

<script>
	import {mapState, mapActions} from 'vuex'
	export default {
		data(){
			return {
				StatusBar: this.StatusBar,
				CustomBar: this.CustomBar,
				list:[],
				searchText: "",
				allData: [],
				filterData: [],
				deep:1,
				index:-1,
				isShow:false,
				cur:0,
				result:null
			}
		},
		computed:{
			checkedNum(){
				if(this.result instanceof Array){
					return this.result.length;
				} else if (this.result instanceof Object){
					if(this.result.name.length > 5){
						return this.result.name.substr(0,5) + "...";
					}
					return this.result.name;
				} else {
					return 0;
				}
			}
		},
		props:{
			url:{
				type: String,
				default: '',
			},
			parentCode:{
				type: String,
				default: '0',
			},
			parentCodeName:{
				type: String,
				default: 'parentCode',
			},
			loadAll: {
				type: Boolean,
				default: false
			},
			title: {
				type: String,
				default: "请选择"
			},
			checkbox: {
				type: Boolean,
				default: false
			},
			icon: {
				type: String,
				default: 'cuIcon-tag'
			},
			type: {
				type: String,
				default: ''
			},
			split: {
				type: String,
				default: " "
			}
		},
		methods:{
			...mapActions(["JAjax"]),
			// 初始化展开一层
			init(){
				uni.showLoading({
					title: '加载中',
					mask: false
				});
				this.list = [];
				// 加载全部数据
				if(this.loadAll){
					this.JAjax({
						url: (this.url.indexOf("?") == -1 ? this.url + "?" : this.url + "&"),
						success: data => {
							let result = data.data;
							// 加载全部数据
							this.allData = result.concat([]);
							// 加载第一层数据
							this.list = [];
							this.allData.forEach((val,key)=>{
								if(val.pId == this.parentCode){
									let first = {}
									first.deep = 0;
									first.icon = "right";
									first.open = true;
									first.show = true;
									first.index = this.cur;
									first.id = val.id;
									first.pId = val.pId;
									first.name = val.name;
									first.isParent = val.isParent || false;
									this.list.push(first);
									// 加载多层数据
									this.loadSubData(val.id, first.deep + 1);
								}
							})
							this.setChecked();
							uni.hideLoading();
						}
					});
				} else {
					// 加载第一层数据
					this.JAjax({
						url: (this.url.indexOf("?") == -1 ? this.url + "?" : this.url + "&") + this.parentCodeName + "=" + this.parentCode,
						success: data => {
							let result = data.data;
							this.list = [];
							result.forEach((val,key)=>{
								let first = {}
								first.deep = 0;
								first.icon = "right";
								first.open = false;
								first.show = true;
								first.index = this.cur;
								first.id = val.id;
								first.pId = val.pId;
								first.name = val.name;
								first.isParent = val.isParent || false;
								this.list.push(first);
							})
							this.setChecked();
							uni.hideLoading();
						}
					});
				}
				
			},
			// 加载全部数据后默认只显示第一层
			loadSubData(pId, deep){
				this.allData.forEach((val,key)=>{
					if(pId == val.pId){
						let tmp = {};
						tmp.deep = deep;
						tmp.icon = "right";
						tmp.open = true;
						tmp.show = false;
						tmp.id = val.id;
						tmp.pId = val.pId;
						tmp.name = val.name;
						tmp.isParent = val.isParent || false;
						this.list.push(tmp);
						this.loadSubData(tmp.id, deep + 1);
					}
				})
			},
			// 隐藏子项
			hideSub(id){
				this.list.forEach((val, ind)=>{
					if(val.pId == id){
						val.show = false;
						val.icon = "right";
						this.hideSub(val.id)
					}
				})
			},
			// 显示隐藏
			setShow(parentCode){
				if(parentCode == "0") return;
				let set = new Set();
				this.allData.forEach((val,ind)=>{
					if(parentCode == true){
						if(val.name.indexOf(this.searchText) != -1){
							val.show = true;
							set.add(val.pId);
						}
					} else if(parentCode != "0"){
						if(val.id == parentCode){
							val.show = true;
							set.add(val.pId)
						}
					} 
					
				})
				for(let item of set.values()){
					this.setShow(item);
				}
			},
			// 搜索过滤
			setSearch(parent, deep){
				this.filterData.forEach((val,ind)=>{
					if(val.pId == parent){
						val.deep = deep;
						val.icon = "down";
						val.open = true;
						val.show = true;
						val.isParent = val.isParent || false;
						this.list.push(JSON.parse(JSON.stringify(val)));
						let pre = this.list.length;
						this.setSearch(val.id, val.deep + 1);
						let end = this.list.length;
						if(pre == end){
							this.list[this.list.length-1].open = false;
							this.list[this.list.length-1].icon = "right";
						}
					}
				})
			},
			// 开始搜索
			search(){
				uni.showLoading({
					title: '加载中',
					mask: false
				});
				this.JAjax({
					url: this.url,
					success: data => {
						let result = data.data;
						this.allData = result.concat([]);
						this.setShow(true);
						this.filterData = [];
						this.list = [];
						this.allData.forEach((val,key)=>{
							if(val.show == true){
								this.filterData.push(val)
							}
						})
						console.log(this.allData.length)
						this.setSearch("0", 0);
						this.setChecked()
						uni.hideLoading()
					}
				});
			},
			// 展开/关闭
			getSubList(id, deep, ind){
				// 选中
				if(this.list[ind].isParent == false){
					// this.$set(this.list[ind], "checked", true)
					// if(this.checkbox){
					// 	this.checkboxChange(ind);
					// } else {
					// 	this.radioChange(ind);
					// }
					return;	
				}
				// 第一次加载
				if(this.list[ind].open == false && this.list[ind].icon == "right"){
					this.JAjax({
						url:(this.url.indexOf("?") == -1 ? this.url + "?" : this.url + "&") +  this.parentCodeName + "=" + id,
						success: data => {
							let result = data.data;
							result.forEach((val,key)=>{
								val.deep = deep + 1;
								val.icon = "right";
								val.open = false;
								val.show = true;
							})
							let end = this.list.splice(ind+1);
							this.list = this.list.concat(data.data).concat(end);
							this.setChecked()
						}
					});
					this.list[ind].icon = "down";
					this.list[ind].open = true;
					return;
				}
				// 第一次关闭
				if(this.list[ind].open == true && this.list[ind].icon == "down"){
					this.hideSub(id);
					this.list[ind].icon = "right";
					return;
				}
				// 再次展开
				if(this.list[ind].open == true && this.list[ind].icon == "right"){
					this.list.forEach((val,key)=>{
						if(val.pId == id){
							val.show = true;
						}
					})
					this.list[ind].icon = "down";
					return;
				}
			},
			// 多选
			checkboxChange(ind){
				let chose = this.list[ind];
				this.$set(chose, "fullName", this.getParentNames(chose.id));
				let isAdd = true;
				this.result.forEach((val,index)=>{
					if(chose.id == val.id){
						isAdd = false;
						this.result.splice(index,1);
						return;
					}
				})
				isAdd ? this.result.push(chose) : '';
			},
			// 单选选中
			radioChange(ind){
				this.result = {};
				this.result = this.list[ind];
				console.log(this.getParentNames(this.result.id))
				this.$set(this.result, "fullName", this.getParentNames(this.result.id));
			},
			setChecked(){
				
				console.log("auto check")
				if(this.checkbox){
					this.list.forEach((val,ind)=>{
						this.result.forEach((value,index)=>{
							if(val.id == value.id){
								this.$set(this.list[ind], "checked", true);
							}
						})
					})
				} else {
					if(this.result == null){
						return;
					}
					console.log(this.result.id)
					console.log("auto radio")
					this.list.forEach((val,ind)=>{
						console.log(val.id)
						if(val.id == this.result.id){
							console.log("auto radio in")
							this.$set(this.list[ind], "checked", true);
						}
					})
				}
				
			},
			clearAll(){
				uni.showModal({
					title: '确认清空所有?',
					success: res => {
						if(res.confirm){
							this.list.forEach((val,ind)=>{
								this.$set(this.list[ind],'checked',false);
							})
							if(this.checkbox){
								this.result = []
							} else {
								this.result = null;
							}
						}
					}
				});
			},
			// 确定
			__confirm(){
				this.$parent.treeselectCallback(this.type, this.result);
				this.isShow = false;
			},
			// 获取父级名称
			getParentNames(id){
				for (let i=0; i < this.list.length; i++){
					if(id == this.list[i].id){
						let res = this.getParentNames(this.list[i].pId);
						return (res == undefined ? "" : res + this.split) + this.list[i].name;
					}
				}
			},
			// 关闭
			__cancel(){
				this.isShow = false;
			},
			// 打开 ids是传入的ID请用逗号隔开
			__show(result){
				this.searchText = "";
				if(this.checkbox){
					if(result && result.length > 0){
						this.result = result;
					} else {
						this.result = [];
					}
				} else {
					console.log(result);
					if(result){
						this.result = {};
						this.result = result;
					} else {
						this.result = null;
					}
				}
				this.isShow = true;
				this.init();
			}
		}
	}
</script>

<style scoped>
	.cu-list>.cu-item {
		transition: all 0s ease-in-out 0s;
		transform: translateX(0upx)
	}
	.hideRow{
		display: none !important;
	}
</style>
